package ex02.pyrmont;

import com.sky.JULLog.MyLogger;

import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Servlet;

/**
 *   把 request 和 response 用门面 包装;
 *
 * */
public class ServletProcessorV2 {


  private  static Logger log  = MyLogger.getLogger(ServletProcessorV2.class);

  public void process(RequestV1 requestV1, ResponseV1 responseV1) {

    String uri = requestV1.getUri();
    String servletName = uri.substring(uri.lastIndexOf("/") + 1);
    URLClassLoader loader = null;

    try {
      // create a URLClassLoader
      URL[] urls = new URL[1];
      URLStreamHandler streamHandler = null;
      File classPath = new File(Constants.WEB_ROOT);
      // the forming of repository is taken from the createClassLoader method in
      // org.apache.catalina.startup.ClassLoaderFactory
      String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString() ;
      // the code for forming the URL is taken from the addRepository method in
      // org.apache.catalina.loader.StandardClassLoader class.
      urls[0] = new URL(null, repository, streamHandler);
      loader = new URLClassLoader(urls);
    }
    catch (IOException e) {
      System.out.println(e.toString() );
    }
    Class myClass = null;
    try {
      myClass = loader.loadClass(servletName);
    }
    catch (ClassNotFoundException e) {
      log.log (Level.SEVERE,  e.toString());
    }

    Servlet servlet = null;
    RequestFacade requestFacade = new RequestFacade(requestV1);
    ResponseFacade responseFacade = new ResponseFacade(responseV1);
    try {
      servlet = (Servlet) myClass.newInstance();
      servlet.service(requestFacade, responseFacade);
    } catch (Throwable e) {
      log.log (Level.SEVERE,  e.toString());
    }

  }
}
